<?php

	include 'hash.php';
	
	$successful = true;

	//get the post variables
	$username = $_POST['username'];
	$password = $_POST['password'];
	
	$query = sprintf("SELECT * FROM CS275.userlogin WHERE username='%s' LIMIT 1", mysql_real_escape_string($username));
	
	//establish connection to MySQL
	$link = mysql_connect('localhost', 'root', 'admin');
	if(!$link){
		$successful = false;
		die('Could not connect: ' . mysql_error());	
	}
	
	//do the first query
	$result = mysql_query($query, $link);
	
	//get the results
	$id;
	$hashPassword;
	if ($result) {
      while($row = mysql_fetch_array($result)) {
        // do something with the $row
		$id = $row["id"];
		$hashPassword = $row["password"];
      }
    }else{
		$successful = false;
	}
	
	//free the result
	mysql_free_result($result);
	
	if($successful){
		$query2 = sprintf("SELECT * FROM CS275.userinfo WHERE id='%s' LIMIT 1", $id);
		
		//do the second query
		$result = mysql_query($query2, $link);
		
		//get the birthday info
		$birthDay;
		$birthMonth;
		$birthYear;
		if($result){
			while($row = mysql_fetch_array($result)){
				$birthDay = $row["birthDay"];
				$birthMonth = $row["birthMonth"];
				$birthYear = $row["birthYear"];	
			}
			
			//if the passwords match let them in
			if($hashPassword != hashPassword($password, $birthDay, $birthMonth, $birthYear)){
				$successful = false;
			}
			
		}else{
			$successful = false;	
		}
		//free the result
		mysql_free_result($result);
	}

	//close MySQL connection
	mysql_close($link);
	
	//make false print false, true for true
	$boolarray = Array(false => 'false', true => 'true');
	
	//output json
	echo(json_encode(array("successful" => $boolarray[$successful], "id" => $id)));

?>